import { ref, watch } from "vue";
import type { Ref } from "vue";
export function useStorage(key: string, value: unknown = null,storage:Storage=localStorage) {
    // val 是ref响应对象
    let val: Ref<unknown>;

    if (value) {
        val = ref(value);
        write();
    } else {
        val = ref(read());
    }

    // 监听    { deep: true }对对象 开启深度监听
    watch(val, write, { deep: true });


    // 基本数据的修改
    function read() {
        return JSON.parse(storage.getItem(key)!);
    }

    // 对象存储方法  或  
    function write() {
        storage.setItem(key, JSON.stringify(val.value as string));
    }

    return val;
}
